from django.shortcuts import render
from django.views import View
from django.http import HttpResponse,JsonResponse,HttpResponseRedirect,Http404
from django.conf import settings
import hashlib
from common.xmlparise import WxHandler,WxReply
from common.wxReply import TuLing
from django.utils.encoding import smart_str
import requests
import json
import re
import logging
from decimal import Decimal
from .models import WeChatTip
import threading
from django.core.mail import send_mail
from common import utils
from django.views.decorators.csrf import csrf_exempt



LOGWxgzh = logging.getLogger('api')


# Create your views here.

class WxReceiveText(View):
    @csrf_exempt
    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(request, *args, **kwargs)
        
    def get(self, request):
        if not self.varify(request):
            return HttpResponse('error')
        return HttpResponse(str(request.GET.get('echostr')))
    
    def post(self,request):
        try:
            # 用于微信验证签名校验
            if not self.varify(request):
                return HttpResponse('error')
            body = request.body
            LOGWxgzh.info(body.decode()) # 记录日志
            xmlHander = WxHandler(smart_str(body))
            toUserName = xmlHander.get_value_by_name('ToUserName')
            fromUserName = xmlHander.get_value_by_name('FromUserName')
            # createTime = xmlHander.get_value_by_name('CreateTime')
            msgType = xmlHander.get_value_by_name('MsgType')
            respInfo = ''
            if msgType == 'event':
                # 用户关注回复信息
                respInfo = self.wx_key_get_info(key_ename='subscribe')
            elif msgType == 'text':
                # 获取用户发送的内容
                content = xmlHander.get_value_by_name('Content')
                # 从数据库中查询是否有关键字
                key_content = self.wx_key_get_info(key_ename=content)
                if key_content:
                    respInfo = key_content
                else:
                    content = TuLing(content).get_content()
                    respInfo = content + "\n" +"-"*20 +"\n" + "关注微信公众号【给点知识】"
            wxReply = WxReply(toUserName,fromUserName,'text')
            wxReply.set_text(respInfo)
            data = wxReply.get_data()
            return HttpResponse(data)
        except  Exception as e:
            LOGWxgzh.error(str(e))
            threading.Thread(target=send_mail(
                '微信公众号出现错误了',
                str(e),
                settings.EMAIL_HOST_USER,
                [settings.WXGZH_ERROR_TIP],
                fail_silently=False,
            )).start()
            # /:handclap 微信表情字符 可去互联网搜一下
            respInfo = '/:handclap I am sleep'
            wxReply.set_text(respInfo)
            data = wxReply.get_data()
            return HttpResponse(str(e))

    def varify(self, request):
        try:
            signature = request.GET.get('signature')
            timestamp = request.GET.get('timestamp')
            nonce = request.GET.get('nonce')
            echostr = request.GET.get('echostr')
            encrypt_type = request.GET.get('encrypt_type')
            token = settings.WX_TOKEN
            sign_list = [token,timestamp,nonce]
            sign_list.sort()
            sha1 = hashlib.sha1()
            # python2.x使用
            # map(sha1.update,sign_list)
            # python3.x使用
            sign_str = ''.join(sign_list)
            sha1.update(bytes(sign_str,'utf8'))
            hashcode = sha1.hexdigest()
            if hashcode != signature:
                return False
            else:
                return True
        except Exception as e:
            LOGWxgzh.error(str(e))
            return False

    def wx_key_get_info(self,key_ename=None,key_cname=None):
        '''
        用户关注公众号提示信息
        '''
        try:
            weChatTip = WeChatTip.objects.filter(key_ename__contains=key_ename).first()
            return weChatTip.content
        except Exception as e:
            LOGWxgzh.error(str(e))
            return None


